package com.bfxy.rabbit.producer.component;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.UUID;

/**
 * @author caryguan
 * @version V1.0
 * @Package com.bfxy.rabbit.producer.component
 * @date 2020/9/29 13:44
 */
@Component //rabbitMQ和springboot集成了,直接打上组件注解
public class RabbitSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //broker应答消息的监听器
    /**
     * 确认消息的回调监听端口,用于确认消息是否broker所收到
     */
    final RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {
        /**
         *
         * @param correlationData 作为一个唯一标识,也可以做自定义
         * @param ack broker是否落盘
         * @param cause 失败的一些异常信息
         */
        @Override
        public void confirm(CorrelationData correlationData, boolean ack, String cause) {

        }
    };

    /**
     * 对外发送消息的方法
     *
     * @param message
     * @param properties
     * @throws Exception
     */
    public void send(Object message, Map<String, Object> properties) throws Exception {
        MessageHeaders mhs = new MessageHeaders(properties);
        Message<?> msg = MessageBuilder.createMessage(message, mhs);

        rabbitTemplate.setConfirmCallback(confirmCallback);

        //指定业务唯一的ID
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        rabbitTemplate.convertAndSend("exchange-1",
                "springboot.rabbit",
                msg,
                new MessagePostProcessor() {
                    @Override
                    public org.springframework.amqp.core.Message postProcessMessage(org.springframework.amqp.core.Message message) throws AmqpException {
                        System.out.println("post to do: "+message);
                        return message;
                    }
                },correlationData );

    }
}












